package mlz.d_desk;

import java.util.ArrayList;
import java.util.List;

/*
    共享资源类
 */
public class Desk {
    private List<String> list = new ArrayList<>();

    //定义一个放包子的方法 -> 厨师线程
    public synchronized void put(){
        //1.获取当前线程的名字
        String name = Thread.currentThread().getName();
        //2.判断是否有包子
        if (list.size() == 0){
            //相当于生产了一个包子
            list.add(name + "做包子");
            System.out.println(name + "做了一个肉包子~~");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            //3.唤醒别人(别的线程),让当前线程进入等待
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }



    //定义一个吃包子的方法 -> 顾客线程
    public synchronized void eat(){
        //1.获取当前线程的名字
        String name = Thread.currentThread().getName();
        //2.判断是否有包子
        if (list.size() == 1){
            //有包子
            System.out.println(name + "吃了" + list.get(0));
            list.clear();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //3.唤醒别人,自己进入等待
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            //3.唤醒别人,自己进入等待
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}






























